package com.chat.server;

import com.chat.data.MySqlSingle;
import com.chat.entity.DataPackage;
import com.chat.entity.ServerAction;
import com.chat.mapper.FileMapper;
import com.chat.mapper.UserMapper;
import com.chat.util.FileUtils;
import com.chat.util.JwtUtils;
import org.apache.ibatis.session.SqlSession;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.DataFormatException;

/**
 * 文件传输服务
 * 1.传输实现思路
 * 把文件转换成二进制流
 * 随后通过DataPackagerServer传输
 * 2.保存实现思路
 * 把文件保存在服务端指定路径
 * 随后把file信息存储到数据库file表中
 *
 *
 */
public class FileServer implements DataPackagerServer{

    FileMapper fileMapper;
    UserMapper userMapper;
    SqlSession sqlSession;

    //文件存储地址
    private static final String STORE_FILE_PATH = "/Users/supeng/Desktop/workspace/java/BackApplication/files";


    public FileServer() throws IOException {
        sqlSession = MySqlSingle.getMySqlSingle().getSqlSessionFactory().openSession();
        fileMapper = MySqlSingle.getMySqlSingle().getSqlSessionFactory().getConfiguration().getMapper(FileMapper.class,sqlSession);
        userMapper = MySqlSingle.getMySqlSingle().getSqlSessionFactory().getConfiguration().getMapper(UserMapper.class,sqlSession);
    }

    /**
     * 写入文件到服务器
     * @param source
     * @throws IOException
     */
    public boolean saveFile(DataPackage source) {
        if(source.getAction()== ServerAction.SEND_FILE_FROM_ROOM){
            Map<String,Object> objectMap = (Map<String, Object>) source.getDate();
            String fileName = (String) objectMap.get("fileName");
            int roomId = (int) objectMap.get("roomId");

            byte[] content = (byte[]) objectMap.get("fileContent");

            //解压
//            content = FileUtils.uncompress(content);

//            File file = new File(STORE_FILE_PATH+"/"+fileName);
//            FileOutputStream fileOutputStream = new FileOutputStream(file);
//            fileOutputStream.write(content);
//            fileOutputStream.flush();
//            fileOutputStream.close();
            FileUtils.saveFile(content,STORE_FILE_PATH,fileName);

            //写入数据库
            com.chat.entity.File fileEntity = new com.chat.entity.File();
            int Userid = userMapper.selectUserByAccount(JwtUtils.getAccount(source.getToken())).getUserId();
            fileEntity.setUserId(Userid);
            fileEntity.setFileName(fileName);
            fileEntity.setRoomId(roomId);
            fileEntity.setFileUrl(STORE_FILE_PATH);
            fileMapper.insertFile(fileEntity);
            sqlSession.commit();
            return true;
        }
        return false;
    }

    /**
     * 获取文件数据
     * @param source
     * @return
     */
    public byte[] getFile(DataPackage source) throws IOException {
        //下载文件
        if(source.getAction()==ServerAction.DOWNLOAD_FILE_FROM_ROOM){
            Map<String,Object> objectMap = (Map<String, Object>) source.getDate();
            int fileId = (int) objectMap.get("fileId");
            com.chat.entity.File entityFile = fileMapper.selectFileById(fileId);
            return FileUtils.downFile(STORE_FILE_PATH,entityFile.getFileName());
//            File file = new File(STORE_FILE_PATH+"/"+entityFile.getFileName());
//            if(file!=null) {
//                FileInputStream fileInputStream = new FileInputStream(file);
//                byte[] content = fileInputStream.readAllBytes();
//                return content;
//            }
        }
        return null;

    }


    @Override
    public DataPackage run(DataPackage source) {
        switch (source.getAction()){
            case SEND_FILE_FROM_ROOM:
                if(saveFile(source)) {
                    return DataPackage.successResponse(null);
                }

            case DOWNLOAD_FILE_FROM_ROOM:

                try {
                    byte[] content = getFile(source);
                    if(content !=null)
                        return DataPackage.successResponse(content);
                } catch (IOException e) {
                    e.printStackTrace();
                }
//                finally {
//                    return DataPackage.failResponse("获取文件失败！");
//                }


            case GET_FILES_FROM_ROOM:
                Map<String,Object> params = (Map<String, Object>) source.getDate();
                int roomId = (Integer) params.get("roomId");
                List<com.chat.entity.File> list = fileMapper.selectFileByRoom(roomId);
                if(list!=null)
                    return DataPackage.successResponse(list);
                break;
        }


        return DataPackage.failResponse("失败");
    }
}
